package com.hesicare.health.worker;

import com.hesicare.adapter.entity.HisStaff;
import com.hesicare.health.entity.SysDept;
import com.hesicare.health.entity.SysUser;
import com.hesicare.health.entity.SysUserDept;
import com.hesicare.health.entity.SysUserRole;
import com.hesicare.health.service.ISysDeptService;
import com.hesicare.health.service.ISysUserDeptService;
import com.hesicare.health.service.ISysUserRoleService;
import com.hesicare.health.service.ISysUserService;
import com.hesicare.untils.MD5Utils.PasswordUtils;
import com.hesicare.untils.StringUtil.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

import static com.hesicare.enums.userEnum.*;

@Component
public class DoUser {

    protected final static Logger LOGGER = LoggerFactory.getLogger(DoUser.class);

    @Autowired
    private ISysUserService ISysUserService;

    @Autowired
    private ISysUserDeptService ISysUserDeptService;

    @Autowired
    private ISysDeptService ISysDeptService;

    @Autowired
    private ISysUserRoleService ISysUserRoleService;

    public synchronized boolean doUser(HisStaff hisStaff) {
        if (!checkUser(hisStaff)) {
            return false;
        }
        SysUser sysUser = ISysUserService.getUserByLoginName(hisStaff.getUsercode());
        if (sysUser == null) {
            sysUser = new SysUser();
            try {
                SysDept sysDept = this.getSysDept(hisStaff);
                if (sysDept == null) {
                    return false;
                }
                this.transform(hisStaff, sysUser);
                this.createUserInfo(hisStaff, sysUser);
                ISysUserService.insertUser(sysUser);
                LOGGER.info("新增员工" + sysUser.toString());
                this.saveDept(hisStaff, sysUser, sysDept);
                SysUserRole sysUserRole = new SysUserRole();
                this.saveRole(hisStaff, sysUserRole, sysUser);
                ISysUserRoleService.insertSysUserRole(sysUserRole);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        } else {
            SysDept sysDept = this.getSysDept(hisStaff);
            this.saveDept(hisStaff, sysUser, sysDept);
            if (!isChange(hisStaff, sysUser)) {
                return false;
            }
            this.transform(hisStaff, sysUser);
            this.updateUserInfo(sysUser);
            ISysUserService.updateUser(sysUser);
            LOGGER.info("更新员工" + sysUser.toString());
            return true;
        }
    }


    public boolean checkUser(HisStaff hisStaff) {
        if (hisStaff == null) {
            return false;
        }
        if (StringUtil.isBlank(hisStaff.getUsercode()) ||
                hisStaff.getStaffId() == null) {
            return false;
        }
        return true;
    }

    public boolean isChange(HisStaff staff, SysUser sysUser) {
        if (!staff.getUsercode().equals(sysUser.getLoginName())) {
            return true;
        }
        if (!staff.getStaffId().equals(sysUser.getHisUserId())) {
            return true;
        }
        if (!staff.getPersonname().equals(sysUser.getUserName())) {
            return true;
        }
        return false;
    }

    public void transform(HisStaff staff, SysUser sysUser) {
        sysUser.setLoginName(staff.getUsercode());
        sysUser.setHisUserId(staff.getStaffId());
        sysUser.setSex(staff.getSex());
        sysUser.setUserName(staff.getPersonname());
        sysUser.setCreateBy(CREATEBY.getType());
        sysUser.setStatus(ZERO.getType());
        sysUser.setDelFlag(ZERO.getType());
    }

    public void createUserInfo(HisStaff staff, SysUser sysUser) {
        sysUser.setSalt(PasswordUtils.randomSalt());
        /**
         * 密码默认111111
         */
        sysUser.setPassword(PasswordUtils.encryptPassword(staff.getUsercode(), PASSWORD.getType(), sysUser.getSalt()));
        sysUser.setCreateBy(CREATEBY.getType());
        sysUser.setUpdateTime(new Date());
        /**
         * 员工默认权限，默认本机构及以下。
         **/
        sysUser.setDataScope(CURRENT.getType());
    }

    public SysUser updateUserInfo(SysUser sysUser) {
        sysUser.setUpdateBy(CREATEBY.getType());
        sysUser.setUpdateTime(new Date());
        return sysUser;
    }

    public SysUser saveDept(HisStaff staff, SysUser sysUser, SysDept sysDept) {
        if (sysDept != null) {
            if (sysUser.getDeptId() == null) {
                sysUser.setDeptId(sysDept.getDept_id());
                ISysUserService.updateUser(sysUser);
                LOGGER.info("新增归属部门" + sysUser.toString());
            }
            /**
             * 若为多科室权限，则需区分‘归属科室’与‘权限科室’，通过staff的ext1字段标识，1为权限科室，其他为归属科室
             * 归属科室需保证只有一个，权限科室可有多个
             */
            if (sysUser.getDeptId() != null && !CUSTOMIZE.getType().equals(sysUser.getDataScope())) {
                sysUser.setDeptId(sysDept.getDept_id());
                ISysUserService.updateUser(sysUser);
                LOGGER.info("修改归属部门" + sysUser.toString());
            }
            this.saveSysUserDept(sysUser.getUserId(), sysDept.getDept_id());
        }
        return sysUser;
    }

    public void saveSysUserDept(Long userId, Long deptId) {
        List<Long> depts = ISysUserDeptService.getSysUserDeptByUserId(userId);
        if (depts == null) {
            saveUserDept(deptId, userId);
        } else if (!depts.contains(deptId)) {
            saveUserDept(deptId, userId);
        }
    }

    public SysDept getSysDept(HisStaff hisStaff) {
        SysDept sysDept = null;
        if (StringUtil.isNotBlank(hisStaff.getDepartment()) && StringUtil.isNotBlank(hisStaff.getWardArea())) {
            sysDept = ISysDeptService.getSysDeptByHisCode(hisStaff.getWardArea());
        }
        if (StringUtil.isNotBlank(hisStaff.getDepartment()) && StringUtil.isBlank(hisStaff.getWardArea())) {
            sysDept = ISysDeptService.getSysDeptByHisCode(hisStaff.getDepartment());
        }
        if (StringUtil.isBlank(hisStaff.getDepartment()) && StringUtil.isNotBlank(hisStaff.getWardArea())) {
            sysDept = ISysDeptService.getSysDeptByHisCode(hisStaff.getWardArea());
        }
        return sysDept;
    }

    private void saveRole(HisStaff staff, SysUserRole sysUserRole, SysUser sysUser) {
        if (staff.getTitle() != null && staff.getTitle().equals(ZERO.getType())) {
            sysUserRole.setRoleId(Long.parseLong(DOCTOR.getType()));
        } else if (staff.getTitle() != null && staff.getTitle().equals(DISABLE.getType())) {
            sysUserRole.setRoleId(Long.valueOf(NURSE.getType()));
        } else {
            sysUserRole.setRoleId(Long.valueOf(ADMIN.getType()));
        }
        sysUserRole.setUserId(sysUser.getUserId());
    }

    public void saveUserDept(Long deptId, Long userId) {
        SysUserDept sysUserDept = new SysUserDept();
        sysUserDept.setDeptId(deptId);
        sysUserDept.setUserId(userId);
        ISysUserDeptService.insertSysUserDept(sysUserDept);
        LOGGER.info("新增权限部门" + sysUserDept.toString());
    }
}
